package com.hunliji.monitor.share.utils;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @author xingfeng
 * @date 2019-07-25
 */
public class AesUtil {

    /**
     * 算法
     */
    private static final String AES = "AES";

    /**
     * 加密算法
     */
    private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    private static int KEY_LENGTH = 16;

    private static BASE64Encoder base64Encoder;

    private static BASE64Decoder base64Decoder;

    static {
        base64Decoder = new BASE64Decoder();
        base64Encoder = new BASE64Encoder();
    }

    /**
     * 加密方法
     * @param secretKey 秘钥，必须为16位
     * @param msg 被加密的字符串
     */
    public static String encrypt(String secretKey, String msg) throws Exception {
        byte[] buffer = msg.getBytes(StandardCharsets.UTF_8);
        byte[] encrypted = change(secretKey, buffer, Cipher.ENCRYPT_MODE);
        return base64Encoder.encode(encrypted);
    }

    /**
     * 解密方法
     * @param secretKey 解密，必须为16位
     * @param msg 要解密的字符串，需要判空，
     */
    public static String decrypt(String secretKey, String msg) throws Exception {
        byte[] buffer = base64Decoder.decodeBuffer(msg);
        byte[] original = change(secretKey, buffer, Cipher.DECRYPT_MODE);
        String originalString = new String(original, StandardCharsets.UTF_8);
        return originalString;
    }

    private static byte[] change(String secretKey, byte[] msg, int mode) throws Exception {
        if (StringUtils.isBlank(secretKey) || secretKey.length() != KEY_LENGTH) {
            throw new IllegalArgumentException("秘钥必须为16位的字符串");
        }

        byte[] raw = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec keySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(mode, keySpec);
        return cipher.doFinal(msg);
    }

    public static void main(String[] args) {
        String secretKey = "1234567890123456";
        String msg = "周金林";
        try {
            String s = encrypt(secretKey, msg);
            System.out.println("加密后：" + s);

            String s1 = decrypt(secretKey, s);
            System.out.println("解密后：" + s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}